package com.sky.ws;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

@Component
@ServerEndpoint("/ws/{sid}")
@Slf4j
public class WebSocketServer {

    private static HashMap<String, Session> sessionHashMap = new HashMap<>();

    /**
     * 建立连接
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid")String sid){
      log.info("客户端"+sid+"与websocket服务建立了连接");
      sessionHashMap.put(sid,session);
    }

    @OnMessage
    public void onMessage(String message,@PathParam("sid")String sid) throws IOException {
        log.info("客户端"+sid+"发来消息:"+message);
    }
    @OnClose
    public void onClose(@PathParam("sid")String sid){
        log.info("客户端"+sid+"断开连接");
        sessionHashMap.remove(sid);
    }

    /**
     * 给所有客户端 群发消息
     * @param message
     */
    public void send2AllClient(String message){
        log.info("服务端给所有客户端发消息"+message);
        Collection<Session> sessions = sessionHashMap.values();
        sessions.forEach(session->{
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
    /**
     * 给所有客户端 群发消息
     * @param message
     */
    public void send2Client(String sid,String message) throws IOException {
        log.info("服务端给所有客户端发消息"+message);
        Session session = sessionHashMap.get(sid);
        session.getBasicRemote().sendText(message);
    }
}
